import axios from 'axios'
import errorCode from './utils/errorCode'

import {
  Message
} from 'element-ui'
import Cookies from 'js-cookie'

axios.defaults.timeout = 3000000;
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500 // 默认的
}

// HTTPrequest拦截
axios.interceptors.request.use(config => {
  if(Cookies.get('Admin-Token') || Cookies.get('QUP-COMPONENT-TOKEN'))
  {
    config.headers['Authorization'] = Cookies.get('Admin-Token') ? `Bearer ${Cookies.get('Admin-Token')}` : `Bearer ${Cookies.get('QUP-COMPONENT-TOKEN')}`
  }
  // config.headers['Authorization'] = `Bearer 600aa5f7-f4be-4976-ad2b-8cb8c60c65a4`
  // // headers中配置serialize为true开启序列化
  if (config.methods === 'post' && config.headers.serialize) {
    config.data = serialize(config.data)
    delete config.data.serialize
  }
  return config
}, error => {
  return Promise.reject(error)
})


// HTTPresponse拦截
axios.interceptors.response.use(response => {
  const res = response.data
  const message = res.msg || errorCode[status] || errorCode['default']
  if (res.success === 0) {
    Message({
      message: message,
      type: 'error'
    })
  }
  const status = Number(response.status) || 200
  if (status === 401 || res.code === 401 || res.code === '401') {
    const postMsgParams = {
      flag: 'refreshToken',
      extraData: {}
    }    
    if (window.parent === window) {
      window.postMessage(postMsgParams, '*')
    }else{
      window.parent.postMessage(postMsgParams, '*')
    }
    return
  }
  if (response.config.responseType === 'blob' || response.config.responseType === 'arraybuffer') {
    return response
  }

  return res
}, error => {
  const res = error.response.data
  const status = Number(error.response.status) || 200
  const message = res.msg || errorCode[status] || errorCode['default']
  if (status === 401 || res.code === 401 || res.code === '401') {
    /* Message({
      message: '登录超时，请重新登录',
      type: 'error',
      duration: 1500,
      onClose: function() {
        if (!window.location.href.includes('/login')) {
          window.location.href = '/login'
        }
      }
    }) */
    const postMsgParams = {
      flag: 'refreshToken',
      extraData: {}
    }
    if (window.parent === window) {
      window.postMessage(postMsgParams, '*')
    }else{
      window.parent.postMessage(postMsgParams, '*')
    }
    return
  }
  if (status !== 200) {
    Message({
      message: message,
      type: 'error'
    })
  }
  return Promise.reject(new Error(error))
})

export default axios
